

package com.maoshi.shop.distribution.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoshi.shop.distribution.comment.dao.*;
import com.maoshi.shop.distribution.comment.dto.AchievementDataDto;
import com.maoshi.shop.distribution.comment.dto.DistributionUserAchievementDataDto;
import com.maoshi.shop.distribution.comment.dto.DistributionUserSimpleDto;
import com.maoshi.shop.distribution.comment.model.DistributionAuditing;
import com.maoshi.shop.distribution.comment.model.DistributionUser;
import com.maoshi.shop.distribution.comment.model.DistributionUserBan;
import com.maoshi.shop.distribution.comment.model.DistributionUserWallet;
import com.maoshi.shop.distribution.comment.param.RangeTimeParam;
import com.maoshi.shop.distribution.comment.param.UpdateDistributionUserParam;
import com.maoshi.shop.distribution.comment.service.DistributionUserService;
import com.maoshi.shop.distribution.comment.service.DistributionUserWalletService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * @author lgh on 2019/04/01.
 */
@Service
@AllArgsConstructor
public class DistributionUserServiceImpl extends ServiceImpl<DistributionUserMapper, DistributionUser> implements DistributionUserService {

    private final DistributionUserMapper distributionUserMapper;

    private final DistributionUserBanMapper distributionUserBanMapper;

    private final DistributionUserBindMapper distributionUserBindMapper;

    private final DistributionAuditingMapper distributionAuditingMapper;

    private final DistributionUserWalletService distributionUserWalletService;

    private final DistributionProdBindMapper distributionProdBindMapper;

    private final DistributionUserIncomeMapper distributionUserIncomeMapper;


    @Override
    @Cacheable(cacheNames = "distribution_user", key = "#shopId + ':' + #userId")
    public DistributionUser getByUserIdAndShopId(String userId, Long shopId) {
        return distributionUserMapper.selectOne(new LambdaQueryWrapper<DistributionUser>().eq(DistributionUser::getUserId, userId).eq(DistributionUser::getShopId, shopId));
    }

    @Override
    @CacheEvict(cacheNames = "distribution_user", key = "#shopId + ':' + #userId")
    public void removeCacheByUserIdAndShopId(String userId, Long shopId) {

    }

    @Override
    public AchievementDataDto getAchievementDataDtoById(Long id) {
        return distributionUserMapper.getAchievementDataDtoById(id);
    }

    @Override
    public DistributionUserAchievementDataDto getDistributionUserLevelAchievementDataByDistributionUserId(Long distributionUserId) {
//        DistributionUser distributionUser=getById(distributionUserId);
        DistributionUserAchievementDataDto distributionUserAchievementDataDto = distributionUserMapper.getLevelDistributionUserAchievementDataByDistributionUserId(distributionUserId);
        //注入购物数据
//        UserShoppingDataDto userShoppingDataDto = orderMapper.calculateUserInShopData(distributionUser.getShopId(), distributionUser.getUserId());
//        distributionUserAchievementDataDto.setUserShoppingDataDto(userShoppingDataDto);
        return distributionUserAchievementDataDto;
    }

    @Override
    public IPage<DistributionUser> distributionUserPage(Page page, DistributionUser distributionUser, RangeTimeParam rangeTimeParam, String mobile, String parentMobile) {
        return distributionUserMapper.distributionUserPage(page, distributionUser, rangeTimeParam, mobile, parentMobile);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSelectiveAndInsertDistributionUserBan(UpdateDistributionUserParam param, Long modifier) {
        //创建ban对象，插入数据后修改分销员状态
        DistributionUserBan distributionUserBan = new DistributionUserBan();
        distributionUserBan.setDistributionUserId(param.getDistributionUserId());
        distributionUserBan.setRemarks(param.getRemarks());
        distributionUserBan.setBanReason(param.getBanReason());
        distributionUserBan.setState(param.getState());
        distributionUserBan.setModifier(modifier);
        distributionUserBan.setUpdateTime(new Date());
        distributionUserBanMapper.insert(distributionUserBan);

        // 更新分销员状态
        DistributionUser distributionUser = new DistributionUser();
        distributionUser.setDistributionUserId(param.getDistributionUserId());
        distributionUser.setState(param.getState());
        distributionUserMapper.updateById(distributionUser);

        //如果是清退或封禁
        if (param.getState() == 2 || param.getState() == -1) {
            //将绑定的用户设为失效
            distributionUserBindMapper.updateStateByDistributionUserId(param.getDistributionUserId(), -1);
            //将商品分享记录设为失效
            distributionProdBindMapper.updateStateByDistributionUserId(param.getDistributionUserId(), -1);
            //判断是否为封禁
            if (param.getState() == -1) {
                //将正在处理中的佣金订单冻结
                distributionUserIncomeMapper.updateStateByDistributionUserId(param.getDistributionUserId(), -1);
            }
        }
    }

    @Override
    public IPage<DistributionUser> getDistributionUserAchievementPage(Page page, DistributionUser distributionUser, String userMobile) {
        return distributionUserMapper.getDistributionUserAchievementPage(page, distributionUser, userMobile);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registerDistributionUser(DistributionUser distributionUser) {

        DistributionUser dbDistributionUser = getByUserIdAndShopId(distributionUser.getUserId(), distributionUser.getShopId());

        // 返回自增id
        Long distributionUserId;

        if (dbDistributionUser == null) {
            //存入分销员数据库
            distributionUserMapper.insert(distributionUser);

            distributionUserId = distributionUser.getDistributionUserId();

            //为这个分销员创建一个钱包
            DistributionUserWallet distributionUserWallet = new DistributionUserWallet();
            distributionUserWallet.setAddupAmount(0.0);
            distributionUserWallet.setSettledAmount(0.0);
            distributionUserWallet.setInvalidAmount(0.0);
            distributionUserWallet.setVersion(0);
            distributionUserWallet.setDistributionUserId(distributionUserId);
            distributionUserWallet.setUnsettledAmount(0.0);
            distributionUserWalletService.save(distributionUserWallet);
        } else {
            dbDistributionUser.setState(0);
            distributionUser.setDistributionUserId(dbDistributionUser.getDistributionUserId());
            distributionUserMapper.updateById(distributionUser);
            distributionUserId = dbDistributionUser.getDistributionUserId();
        }


        //创建申请记录该用户是否为本店分销员
        DistributionAuditing distributionAuditing = new DistributionAuditing();
        distributionAuditing.setAuditingTime(new Date());
        distributionAuditing.setShopId(distributionUser.getShopId());
        distributionAuditing.setDistributionUserId(distributionUserId);
        distributionAuditing.setParentDistributionUserId(distributionUser.getParentId());

        //符合条件，自动通过
        if (Objects.equals(distributionUser.getState(),1)) {
            distributionAuditing.setRemarks("系统判断自动通过审核");
            distributionAuditing.setState(1);
        } else {
            distributionAuditing.setState(0);
        }
        if (dbDistributionUser == null) {
            //存入申请记录
            distributionAuditingMapper.insert(distributionAuditing);
        } else {
            DistributionAuditing dbAuditing = distributionAuditingMapper.selectOne(new LambdaQueryWrapper<DistributionAuditing>().eq(DistributionAuditing::getDistributionUserId, distributionUserId));
            distributionAuditing.setAuditingId(dbAuditing.getAuditingId());
            distributionAuditingMapper.updateById(distributionAuditing);
        }






    }

    @Override
    public IPage<DistributionUserSimpleDto> getDistributionUserSimpleDtoByParentUserIdPage(Page page, Long parentDistributionUserId) {
        return distributionUserMapper.getDistributionUserSimpleDtoByParentUserIdPage(page, parentDistributionUserId);
    }


    @Override
    @Cacheable(cacheNames = "distribution_user_by_card_no", key = "#cardNo")
    public DistributionUser getByCardNo(String cardNo) {
        return distributionUserMapper.selectOne(new LambdaQueryWrapper<DistributionUser>().eq(DistributionUser::getCardNo, cardNo));
    }

    @Override
    @CacheEvict(cacheNames = "distribution_user_by_card_no", key = "#cardNo")
    public void removeCacheByCardNo(String cardNo) {

    }

}
